package com.foreveross.fetl.web.action.preprocess;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.foreveross.fetl.common.vo.ShenhangPriceVO;
import com.foreveross.fetl.core.domain.single.SinglePlaneInfoEntity;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.web.action.BaseAction;

@Controller("shenhangLowestPriceAction")
@Scope("prototype")
public class ShenhangLowestPriceAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6967515478204812597L;

	public String list(){
		return "METHOD";
	}
	
	public String downLoad(){
		String fileName="shenHang_"+DateUtils.format(new Date(), "yyyyMMdd")+".xlsx";
		XSSFWorkbook  workbook = null;
		OutputStream os = null;
		InputStream fis=null;
		File file=null;
		HttpServletResponse response=getResponse();
		try {
			workbook = new XSSFWorkbook();
			 XSSFSheet sheet = workbook.createSheet(DateUtils.format(new Date(), "yyyy-MM-dd HHmm"));
			 sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));
			 XSSFRow row = sheet.createRow(0);
			 XSSFCell cell = row.createCell(0);
			 cell.setCellValue("出发地");
			 
			 sheet.addMergedRegion(new CellRangeAddress(0,1,1,1));
			 cell = row.createCell(1);
			 cell.setCellValue("到达地");
			 List<String> lines =this.listLine();
			 int column=2;
			 row=sheet.createRow(1);
			 for(String line:lines){
				 String[] citys=line.split("-");
				 row = sheet.createRow(column);
				 cell=row.createCell(0);
				 cell.setCellValue(citys[0]);
				
				 cell=row.createCell(1);
				 cell.setCellValue(citys[1]);
				 column++;
			 }
			 Calendar c=Calendar.getInstance();
			 List<ShenhangPriceVO> listVo=new ArrayList<ShenhangPriceVO>();
			 List<SinglePlaneInfoEntity> listSingel=null;
			 SinglePlaneInfoEntity singlePlaneInfo =new SinglePlaneInfoEntity();
			 for(int i=0;i<7;i++){
				 c.add(Calendar.DAY_OF_MONTH, 1);
				 String flightDate=DateUtils.format(c.getTime(), "yyyy-MM-dd");
				 
				 sheet.addMergedRegion(new CellRangeAddress(0,0,2+i*6,7+i*6));
				 
				 row=sheet.getRow(0);
				 cell = row.createCell(2+i*6);
				 cell.setCellValue(flightDate);
				 
				 for(String line:lines){
					 ShenhangPriceVO vo =new ShenhangPriceVO();
					 String[] citys=line.split("-");
					 vo.setFromCity(citys[0]);
					 vo.setToCity(citys[1]);
					 String flightNo=null;
					 listSingel=singlePlaneInfo.findPlaneInfoProperty("20000", null, citys[0], citys[1], flightDate, null,null);
					 if(null!=listSingel && listSingel.size()>0){
						 SinglePlaneInfoEntity lowest=this.getLowestEntiy(listSingel);
						 vo.setPrice(lowest.getTotalLowestPrice());
						 flightNo=lowest.getFlightNo();
						 vo.setFlightNo(flightNo);
					 }else{
						 vo.setPrice(0d);
					 }
					 listSingel.clear();
					 
					 listSingel=singlePlaneInfo.findPlaneInfoProperty("20005", null, citys[0], citys[1], flightDate, null,null);
					 if(null!=listSingel && listSingel.size()>0){
						 SinglePlaneInfoEntity lowest=this.getLowestEntiy(listSingel);
						 vo.setCzPrice(lowest.getTotalLowestPrice());
						 vo.setCzFlightNo(lowest.getFlightNo());
					 }else{
						 vo.setCzPrice(0d);
					 }
					 
					 listSingel.clear();
					 listSingel=singlePlaneInfo.findPlaneInfoProperty("00002", null, citys[0], citys[1], flightDate, flightNo,null);
					 if(null!=listSingel && listSingel.size()>0){
						 SinglePlaneInfoEntity lowest=this.getLowestEntiy(listSingel);
						 vo.setQuerePrice(lowest.getTotalLowestPrice());
						
					 }else{
						 vo.setQuerePrice(0d);
					 }
					 listSingel.clear();
					 listSingel=singlePlaneInfo.findPlaneInfoProperty("00003", null, citys[0], citys[1], flightDate, flightNo,null);
					 if(null!=listSingel && listSingel.size()>0){
						 SinglePlaneInfoEntity lowest=this.getLowestEntiy(listSingel);
						 vo.setCriptPrice(lowest.getTotalLowestPrice());
						
					 }else{
						 vo.setCriptPrice(0d);
					 }
					 listVo.add(vo);
				 }
				this.writeToexcel(listVo,sheet,2+i*6) ;
				listVo.clear();
			 }
			   file=new File(fileName);
			  os = new FileOutputStream(file);  
			  workbook.write(os);
		      os.close();
		      
		        response.reset();
				OutputStream toClient = new BufferedOutputStream(
						response.getOutputStream());
				response.setContentType("application/vnd.ms-excel");
				
				String filename=null;
				if (getRequest().getHeader("User-Agent").toLowerCase()
						.indexOf("firefox") > 0) {
					filename = new String(file.getName().getBytes("UTF-8"), "ISO8859-1");// firefox浏览器
				} else {
					filename = URLEncoder.encode(file.getName(), "UTF-8");// 其他浏览器
				}
				response.setHeader("Content-Disposition", "attachment; filename="
						+ filename);// 设定输出文件头
				
				fis = new BufferedInputStream(new FileInputStream(
						file.getPath()));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
		      
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(null!=file)
			   file.delete();
			if(null!=os){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=fis){
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	private void writeToexcel(List<ShenhangPriceVO> listVo, XSSFSheet sheet,int cellSize) {
		XSSFRow row = sheet.getRow(1);
	    int size=row.getLastCellNum();
	    if(size>0){
	    	cellSize=size;
	    }
	    XSSFCell cell = row.createCell(cellSize);
	    cell.setCellValue("深航航班");
	    cell = row.createCell(cellSize+1);
	    cell.setCellValue("深航B2C");
	    cell = row.createCell(cellSize+2);
	    cell.setCellValue("携程");
	    cell = row.createCell(cellSize+3);
	    cell.setCellValue("去哪儿");
	    cell = row.createCell(cellSize+4);
	    cell.setCellValue("南航航班");
	    cell = row.createCell(cellSize+5);
	    cell.setCellValue("南航航B2C");
	    int rowSize=2;
	    for(ShenhangPriceVO vo:listVo){
	    	row = sheet.getRow(rowSize);
	    	if(null==row){
	    		row = sheet.createRow(rowSize);
	    	}
	    	cell = row.createCell(cellSize);
	 	    cell.setCellValue(vo.getFlightNo());
	 	    cell = row.createCell(cellSize+1);
	 	    cell.setCellValue(vo.getPrice());
	 	    cell = row.createCell(cellSize+2);
	 	    cell.setCellValue(vo.getCriptPrice());
	 	    cell = row.createCell(cellSize+3);
	 	    cell.setCellValue(vo.getQuerePrice());
	 	    cell = row.createCell(cellSize+4);
	 	    cell.setCellValue(vo.getCzFlightNo());
	 	    cell = row.createCell(cellSize+5);
	 	    cell.setCellValue(vo.getCzPrice());
	    	rowSize++;
	    }
		
	}

	private SinglePlaneInfoEntity getLowestEntiy(
			List<SinglePlaneInfoEntity> listSingel) {
		SinglePlaneInfoEntity en =new SinglePlaneInfoEntity();
		for(SinglePlaneInfoEntity entity:listSingel){
			if(null==entity.getTotalLowestPrice() || entity.getTotalLowestPrice()==0)
				continue;
			if(null==en || null==en.getTotalLowestPrice()){
				en=entity;
			}else if(en.getTotalLowestPrice()>entity.getTotalLowestPrice()){
				en=entity;
			}
		}
		if(null==en.getTotalLowestPrice())
			en.setTotalLowestPrice(0d);
		return en;
	}

	private  List<String> listLine(){
		List<String> list=new ArrayList<String>();
		Collections.addAll(list, "SZX-PEK", "HRB-SZX", "SHE-CAN", "SZX-SHE",
				"CAN-SHE", "SZX-CKG", "HRB-CAN", "SZX-HRB", "SHE-SZX",
				"CAN-HRB", "CKG-SZX", "SZX-CGQ", "CGQ-SZX", "SHA-SZX",
				"SZX-CTU", "SZX-SHA", "SZX-KMG", "CTU-SZX", "SZX-NKG",
				"WUX-SZX", "SZX-WUX", "SZX-PVG", "NKG-SZX", "PVG-SZX",
				"CAN-CGQ", "CAN-WUX", "SZX-HFE", "SZX-CGO", "SZX-KWE",
				"CGO-SZX", "SZX-LJG", "CAN-KMG", "NKG-KWE", "HFE-SZX",
				"NKG-CAN", "KMG-CAN", "SZX-HGH", "SHE-KMG", "SZX-TYN",
				"KMG-SHE", "CAN-NKG", "KWE-SZX", "WUX-CAN", "CGQ-CAN",
				"SZX-DLC", "HGH-SZX", "CAN-TNA", "SZX-TAO", "NNG-SZX",
				"SZX-XNN");
		return list;
	}
	
	
}
